#include <iostream>
#include <opencv2/opencv.hpp>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <json/json.h>

#include"aip-cpp-sdk-4.16.6/face.h"
using namespace std;
using namespace cv;
using namespace aip;
using namespace Json;

Mat frame;
Mat image;
Rect area;
VideoCapture cam;
pthread_mutex_t g_mutex;
string message;
string retMe;
int a= 0;

const string g_app_id = "45827556";
const string g_api_key = "dTfE2VhapyDCjaTpPFP61zSf";
const string g_secret_key = "tN1K0eqxQHGbZw8NwrEL9wcB0I1PDtUa";
// 打开摄像头
bool open_camera()
{
cam.open(0);
return cam.isOpened();
}

void search_face (Mat &image,Rect &area)
{//将图片里的人脸扣出来
    Mat face_image(image,area);
    //将文件转为通用
     vector<unsigned char>buf;
     imencode(".jpg",face_image,buf);
     //将文件转为BASE64编码
     string base64 =base64_encode((char *)buf.data(), buf.size());
     Face client(g_app_id, g_api_key, g_secret_key);
     string image_type = "BASE64";
     string group_list = "group";
     Json::Value options;
     Json::Value result = client.face_search_v3(base64, image_type, group_list,
     options);
     cout << result << endl;
     if(result["error_msg"]!="SUCCESS"){
          return ;
          }
     float score = result["result"]["user_list"][0]["score"].asFloat();
     cout<< score << endl;
     if(score>80){
     string id = result["result"]["user_list"][0]["user_id"].asString();
     cout << id << endl;
      // 向客户端发送信息
    message = id + "  " + to_string(score);
    // send(client_fd, message.c_str(), message.length(), 0);
    // returnMess(message);
    getMess(message);
}
     //cout<< score << endl;
     //cout << id << endl;
    }

string encode_image()
{
// 先把图像压缩成JPEG格式
vector<unsigned char> buf;
imencode(".jpg", frame, buf);
// 把vector转成string
return string(buf.begin(), buf.end());
}
void *collect_image(void *arg)
{
while(1)
{
usleep(20000);
cam.read(frame);
if (area != Rect(0, 0, 0, 0)) {
    
         if (a >5){
             search_face(frame, area);
             a = 0;
         }
rectangle(frame, area, Scalar(0, 255, 0), 2);

}
#if 0
if(!frame.empty())
{
imshow("xust",frame);
}
if(waitKey(10)!=255)
{
exit(0);
}
#endif 
}
}
void *detect_face(void *arg)
{
CascadeClassifier cls;
cls.load("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml");
while(1)
{
if(!frame.empty())
{
Mat gray;
cvtColor(frame,gray,COLOR_BGR2GRAY);
equalizeHist(gray,gray);
vector<Rect> areas;
cls.detectMultiScale(gray,areas);
if (areas.size() > 0) {
area = areas[0];
a++;
}
else{
area = Rect(0, 0, 0, 0);
}

cout<<"size:"<<areas.size()<<endl;
}
}
void getMess(string mess){
    retMe = mess;
}


